import pandas as pd
from mootdx.quotes import Quotes
from mootdx.reader import Reader
from mootdx.utils.adjust import fq_factor

from ..common.code import code_to_sz_sh_symbol
from ..common.date import date_format


def init_tdx(path):
    """
    初始化mootdx客户端
    """
    client = Quotes.factory(market='std', multithread=True, heartbeat=True, bestip=False, timeout=15)
    reader = None
    if path is not None:
        reader = Reader.factory(market='std', tdxdir=path)
    if reader is not None:
        return client, reader
    return client


def get_transactions(client, symbol, date):
    """
    拿到某只股票某个日期的分笔成交数据
    """
    bars0 = client.transactions(symbol=symbol, start=2000, offset=4000, date=date)
    bars1 = client.transactions(symbol=symbol, start=0, offset=2000, date=date)
    return pd.concat([bars0, bars1], axis=0)


def get_price_shareing_table_by_date_list(client, symbol, date_list, parttern_old, parttern_new):
    """
    通过日期列表的方式获取分价表
    """
    total_minutes_df = minutes(client, symbol, date_list, parttern_old, parttern_new)
    return minutes_to_price_shareing_table(total_minutes_df)


def get_price_shareing_table_by_date_list_adj_price(client, symbol, date_list, parttern_old, parttern_new, adj_way):
    """
    通过日期列表的方式获取分价表
    """
    total_minutes_df = minutes_adj(client, symbol, date_list, parttern_old, parttern_new, adj_way)
    return minutes_to_price_shareing_table_adj_price(total_minutes_df)


def minutes(client, symbol, date_list, parttern_old, parttern_new):
    """
    历史分时
    """
    total_his_minutes_df = pd.DataFrame()
    for date in date_list:
        date = date_format(date, parttern_old, parttern_new)
        minutes_df = client.minutes(symbol=symbol, date=date)
        # minutes_df = client.get_transactions(symbol=symbol, date=date)
        total_his_minutes_df = pd.concat([minutes_df, total_his_minutes_df], axis=0)
        total_his_minutes_df['amounts'] = total_his_minutes_df['price'] * total_his_minutes_df['vol']
    return total_his_minutes_df


def minutes_adj(client, symbol, date_list, parttern_old, parttern_new, adj_way):
    """
    历史分时
    """
    fq_factors = fq_factor(adj_way, code_to_sz_sh_symbol(symbol))
    total_his_minutes_df = pd.DataFrame()
    for date in date_list:
        date = date_format(date, parttern_old, parttern_new)
        minutes_df = client.minutes(symbol=symbol, date=date)
        # minutes_df = client.get_transactions(symbol=symbol, date=date)
        adj_factor = fq_factors[fq_factors['date'] <= date].head(1)
        if minutes_df.empty:
            continue
        price = minutes_df['price'].astype('float')
        # minutes_df.loc[:, 'fq_price'] = price * float(adj_factor[adj_way])
        minutes_df['fq_price'] = round(price / float(adj_factor[adj_way]), 2)
        minutes_df.loc[:, 'fq'] = float(adj_factor[adj_way])
        total_his_minutes_df = pd.concat([minutes_df, total_his_minutes_df], axis=0)
        total_his_minutes_df['amounts'] = total_his_minutes_df['price'] * total_his_minutes_df['vol']
    return total_his_minutes_df


def minutes_to_price_shareing_table_adj_price(minutes_df):
    """
    分时数据转换为分价表
    """
    minutes_df = minutes_df.groupby(['fq_price'], as_index=False)['amounts'].sum()
    return minutes_df.sort_values(by='amounts', ascending=[False]).reset_index()


def minutes_to_price_shareing_table(minutes_df):
    """
    分时数据转换为分价表
    """
    minutes_df = minutes_df.groupby(['price'], as_index=False)['amounts'].sum()
    return minutes_df.sort_values(by='amounts', ascending=[False])


def get_up_and_down_max_amount_price(client, symbol, end_date, base_price):
    klines = client.k(symbol=symbol, begin="1991-06-22", end=end_date)
    close_new = klines['close'][-1]
    if base_price is not None:
        close_new = base_price
    price_shareing_table = get_price_shareing_table_by_date_list_adj_price(client, symbol, klines['date'], '%Y-%m-%d',
                                                                           '%Y%m%d', 'qfq_factor')
    price_shareing_table = price_shareing_table.sort_values(by='fq_price', ascending=[False]).reset_index(drop=True)
    down_max_table = price_shareing_table[close_new >= price_shareing_table['fq_price']].sort_values('amounts',
                                                                                                     ascending=[
                                                                                                         False]).head(1)
    up_max_table = price_shareing_table[close_new <= price_shareing_table['fq_price']].sort_values('amounts',
                                                                                                   ascending=[
                                                                                                       False]).head(1)
    down_rate = (down_max_table['fq_price'] - close_new) / close_new * 100
    up_rate = (up_max_table['fq_price'] - close_new) / close_new * 100
    stat_df = pd.DataFrame([[close_new, float(up_max_table['fq_price']), float(up_max_table['amounts']),
                             round(float(up_rate), 2), float(down_max_table['fq_price']),
                             float(down_max_table['amounts']), float(down_rate)]],
                           columns=['close', 'up_price', 'up_amount',
                                    'up_rate', 'down_price',
                                    'down_amount', 'down_rate'])
    return stat_df
